package com.example.zhou.filehelper;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.zhou.musicmodel.MusicBean;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by 11065 on 2016/11/10.
 */

public class FileToJson {

    private final static String filename = "music_file.json";
    public File file;
    private Context context;


    public static String read(Context context) {
        String ret = "";
        fileExist(context);
        try {
            InputStream inputStream = context.openFileInput(filename);
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ((receiveString = bufferedReader.readLine()) != null) {
                    stringBuilder.append(receiveString);
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    private static String writeJson() {
        List<MusicBean> musicBeen = FileUtil.getMusic(new FileHelper().getMp3());
        return JSON.toJSONString(musicBeen);
    }


    public static void writeToFile(Context context) {

        fileExist(context);
        try {
            OutputStream outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
            outputStream.write(writeJson().getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static File fileExist(Context context) {
        File file = new File(context.getFilesDir().getPath() + filename);
        if (!file.exists()) {
            return createFile(context);
        }
        return file;
    }

    private static File createFile(Context context) {
        return new File(context.getFilesDir(), filename);
    }

}
